package com.j1ay.forum.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.j1ay.forum.model.pojo.vo.ErrorCode;
import com.j1ay.forum.model.pojo.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author J1ay
 * @Date 2021/12/19 16:54
 * @Description Security 自定义无凭证处理类，用户没有携带凭证
 */

@Component
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.info("token失效或者没有携带");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(result));

    }
}
